<?php
namespace app\admin\controller;

use app\admin\model\VoteInfo;
use app\admin\model\VoteOption;

class Vote extends Verify
{
    /**
     * index 首页
     * @return \think\response\View
     * @author isGu
     * @date 2019-12-30 15:41
     */
    public function index()
    {
        $data = $this->initData();
        $data['current'] = 'vote';
        $vote_list = VoteInfo::all(['delete_time' => 0]);
        $data['vote_list'] = $vote_list;
        return view('index', $data);
    }

    /**
     * edit 编辑
     * @return \think\response\View
     * @author isGu
     * @date 2019-12-30 15:41
     */
    public function add()
    {
        $data = $this->initData();
        $data['current'] = 'vote';
        $data['voteInfo'] = null;
        $data['id'] = '';
        return view('edit', $data);
    }

    /**
     * edit 编辑
     * @return \think\response\View
     * @author isGu
     * @date 2019-12-30 15:41
     */
    public function edit()
    {
        $id = input('id');
        $data = $this->initData();
        $data['current'] = 'vote';
        $data['voteInfo'] = [];
        $data['id'] = $id;
        $info = VoteInfo::get($id);
        if (!$info) {
            return $this->error('记录不存在', 'Vote/index');
        }
        return view('edit', $data);
    }

    /**
     * editPost
     * @throws \think\exception\DbException
     * @author isGu
     * @date 2019-12-30 19:00
     */
    public function editPost()
    {
        $id = input('id');
        $title = input('title');
        $description = input('description');
        $option_arr = array_filter($_POST['option']);
        $info = new VoteInfo();
        $vote_data = [
            'title' => $title,
            'description'   => $description
        ];
        if ($id) {
            $info = VoteInfo::get($id);
        } else {
            $vote_data['create_time'] = time();
            $vote_data['voter'] = 0;
        }

        //添加失败
        if (!$info->save($vote_data)) {
            exit(json_encode(['status'  => 1000, 'info' => '添加失败']));
        }

        if (!$id) {
            foreach ($vote_data as $key => $val) {
                $optionModel = new VoteOption();
                $optionModel->save([
                    'option_name'   => $val,
                    'vote_id'       => $info->id
                ]);
            }
        }

        exit(json_encode(['status'  => 200, 'info' => '添加失败']));

    }

    /**
     * del 删除
     * @author isGu
     * @date 2019-12-30 15:41
     */
    public function del()
    {
        $id = input('id');
        $info = VoteInfo::get($id);
        $info->delete_time = time();
        $info->save();

    }
}
